// pages/map/map.js
var app = getApp(); //获取应用实例
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDetail: false,
    isNavigation: false,
    longitude: 113.324520,
    latitude: 23.099994,
    markers: [],
    polyline: [],
    isRender: false,
    isLocation: false,
    detail: {},
    index: -1,
    navigationTypeIndex: 0,
    navigationType: [
      //   {
      //   isAction: true,
      //   text: '驾车',
      //   direction: 'driving'
      // },
      {
        isAction: true,
        text: '步行',
        direction: 'walking'
      }
      // , {
      //   isAction: false,
      //   text: '骑行',
      //   direction: 'bicycling'
      // }
      // , {
      //   isAction: false,
      //   text: '公交',
      //   direction: 'transit'
      // }
    ]
  },
  openMap: function() {
    wx.openLocation({
      latitude: this.data.markers[this.data.index].latitude, // 纬度，范围为-90~90，负数表示南纬
      longitude: this.data.markers[this.data.index].longitude, // 经度，范围为-180~180，负数表示西经
      name: this.data.markers[this.data.index].name,
      address: this.data.markers[this.data.index].address
    })
  },
  navigationSelect: function(e) {
    var index = e.currentTarget.dataset.index;
    if (this.data.navigationTypeIndex == index) {
      return false;
    }
    this.data.navigationType[this.data.navigationTypeIndex].isAction = false;
    this.data.navigationType[index].isAction = true;
    this.setData({
      navigationTypeIndex: index,
      navigationType: this.data.navigationType
    })
    this.navigation({});
  },
  callouttap: function(e) {
    this.setData({
      isDetail: true,
      index: e.markerId
    })
  },
  hiddenDetail: function(e) {
    this.setData({
      isDetail: false,
    })
  },
  signIn: function(e) {
    this.setData({
      isDetail: false
    })
    wx.navigateTo({
      url: '../signIn/signIn?storeId=' + this.data.markers[this.data.index].y_id + '&address=' + this.data.markers[this.data.index].address
    })
  },
  navigation: function(e) {
    this.setData({
      isDetail: false,
      isNavigation: true
    })
    // return false;
    var _this = this;
    let from = this.data.latitude + ',' + this.data.longitude
    let to = this.data.markers[this.data.index].latitude + ',' + this.data.markers[this.data.index].longitude
    //网络请求设置
    app.requestAPI.getDirectionSign({
      from: from,
      to: to,
      direction: this.data.navigationType[this.data.navigationTypeIndex].direction
    }).then(ret => {
      if (ret.status != 0) return; //服务异常处理
      var coors = ret.result.routes[0].polyline,
        pl = [];
      //坐标解压（返回的点串坐标，通过前向差分进行压缩）
      var kr = 1000000;
      for (var i = 2; i < coors.length; i++) {
        coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
      }
      //将解压后的坐标放入点串数组pl中
      for (var i = 0; i < coors.length; i += 2) {
        pl.push({
          latitude: coors[i],
          longitude: coors[i + 1]
        })
      }
      //设置polyline属性，将路线显示出来
      _this.setData({
        polyline: [{
          points: pl,
          color: '#0091ffDD',
          width: 3
        }]
      })
    }).catch(e => {
      app.tip.log('getIndex请求异常')
    });
  },
  getData: function(params) {
    var that = this
    app.requestAPI.findAllByLabelIds(params)
      .then(d => {
        let markers = [];
        if (d.code == 200) {
          for (var index in d.data) {
            let item = d.data[index];
            let marker = {
              id: index,
              y_id: item.id,
              latitude: item.latitude,
              longitude: item.longitude,
              name: item.name,
              telephone: item.telephone,
              brand: item.brand,
              address: item.address,
              width: '40rpx',
              height: '50rpx',
              iconPath: '../image/location.png',
              callout: {
                content: item.brand + "\n\n" + item.address + "\n\n查看详情",
                display: 'BYCLICK',
                borderRadius: 15,
                bgColor: '#1D1C2568',
                padding: '13px 18px',
                color: '#ffffff'
              }
            };
            markers.push(marker)
          }

          that.setData({
            markers: markers
          })
        }else if(d.code == 400){
          that.setData({
            markers: []
          })
          app.tip.modal('搜索不到相关门店')
        } else {
          that.setData({
            markers: []
          })
        }
        that.renderMap();
      }).catch(e => {
        app.tip.log('getIndex请求异常')
      });
  },
  tel: function() {
    wx.makePhoneCall({
      phoneNumber: this.data.markers[this.data.index].telephone,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // this.navigation();
    // return false;
    console.log(options)
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        that.setData({
          isLocation: true,
          longitude: res.longitude,
          latitude: res.latitude
        })
        that.renderMap();
      }
    })
    var params = {};
    if (!!options.id) {
      params.labelIds = options.id
    }
    if (!!options.keyword) {
      params.keyword = options.keyword
    }

    this.getData(params);
  },
  renderMap: function() {
    // if (this.data.markers.length > 0 && this.data.isLocation) {
    this.setData({
      isRender: true
    })
    // }
  },
  markertap(e) {
    console.log(e.markerId)
  },
  formSubmit: function(e) {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.mapCtx = wx.createMapContext('map')
    // var that = this;
    // that.mapCtx.moveToLocation()
    // this.includePoints();
  },
  includePoints: function() {
    this.mapCtx.includePoints({
      padding: [10],
      points: [{
        latitude: 23.10229,
        longitude: 113.3345211,
      }, {
        latitude: 23.00229,
        longitude: 113.3345211,
      }]
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})